<?php

// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array  $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int    $size      大小
     * @param string $delimiter 分隔符
     * @param int    $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int    $time   时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time  时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string  $url    资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname  目录
     * @param bool   $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest   目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items  数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column("{$primary},{$v['column']}") : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $v[$fieldsArr[$n]['display']] = implode(',', array_intersect_key($result[$n], $curr));
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed   $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                header('HTTP/1.1 403 Forbidden');
                exit;
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                exit;
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('csv_to_array')) {
	function csv_to_array($filename='', $delimiter=',')
	{
		if(!file_exists($filename) || !is_readable($filename))
			return FALSE;

		$header = NULL;
		$data = array();
		if (($handle = fopen($filename, 'r')) !== FALSE)
		{
			while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
			{
				if(!$header)
					$header = $row;
				else
					$data[] = array_combine($header, $row);
			}
			fclose($handle);
		}
		return $data;
	}
}

if (!function_exists('cmf_get_website_value')) {
	/**
	 * ksbao 合作者信息
	 */
	function cmf_get_website_value($key='') {
		$website = array(
			"domain" => "vip.niukewang.com",
			"client_ip" => "120.24.163.188",
			"initpasswd" => "kaoguo8",
			"partnercode" => "7aJnyewSy9tFsmegrBH75JSvxUX5zRh7",
			"userAgent" => "100052-1",
		);
		if (empty($key)){
			return $website;
		} else {
			return $website[$key];
		}
	}
}

if (!function_exists('cmf_get_ksbao_value')) {
	/**
	 * 获取考试宝参数
	 *
	 * @return string
	 */
	function cmf_get_ksbao_value($key='') {
		$ksbao = array(
			"regist" => "https://apinew.ksbao.com/api/user/syncRegist",
			"setpass" => "https://apinew.ksbao.com/api/user/setPassword",
			"login" => "https://apinew.ksbao.com/api/user/userlogin",
			"nlogin" => "https://slb-user.ksbao.com/api/user/partnerlogin",
			"nregist" => "https://slb-user.ksbao.com/api/user/syncRegist",
			//"nregist" => "https://slb-user-test.ksbao.com/api/user/syncRegist",
		);
		if (empty($key)) {
			return $ksbao;
		} else {
			return $ksbao[$key];
		}
	}
}


if (!function_exists('cmf_get_ksbao_sendcdk_param')) {
	/*
	* 获取考试宝自动发码的一些参数
	*/
	function cmf_get_ksbao_sendcdk_param($key=''){
		/* $ksbao = [
			'domain'=>'http://101.37.24.216:9001',
			'sendcdk'=>'/rpc/thirdAgent/directPay',     //自动发码
			'sendcdk_again'=>'/rpc/thirdAgent/retryDirectOrder',  // 补发
			'getclass'=>'/rpc/thirdAgent/vnandappclass',   // 获得班次
			'secretKey'=>'8E30CC15D38393054913071593B01AE2',   // 秘钥
			'agent_code'=>'999',   // 代理商代码
		]; */
		$ksbao = [
			'domain'=>'http://smp-api.yingedu.com',
			'sendcdk'=>'/rpc/thirdAgent/directPay',     //自动发码
			'sendcdk_again'=>'/rpc/thirdAgent/retryDirectOrder',  // 补发
			'getclass'=>'/rpc/thirdAgent/vnandappclass',   // 获得班次
			'secretKey'=>'0263ED83BC5D0B6A0BA65D4F993FD6C7',   // 秘钥
			'agent_code'=>'100052-1',   // 代理商代码
		];
		if (empty($key)) {
			return $ksbao;
		} else {
			return $ksbao[$key];
		}
	}
}

if (!function_exists('cmf_get_zhukao_sign')) {
	/*
	* 获取考试宝自动发码的一些参数
	*/
	function cmf_get_zhukao_sign(){
		
			return "助考宝典";//短信签名
	}
}


if (!function_exists('cmf_is_mobile')) {
	/*
	* 检查是不是手机访问
	*/
	function cmf_is_mobile()
	{
		return \think\Request::instance()->isMobile();
	}
}


if (!function_exists('cmf_check_mobile')) {
	/*
	* 检查是不是正确的手机号
	*/
	function cmf_check_mobile($mobile)
	{	
		if(strlen($mobile) != 11) return false;
		if (preg_match('/(^(13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{8})$/', $mobile)) {
			return true;
		} else {
			if (preg_match('/^\d{1,4}-\d{5,11}$/', $mobile)) {
				if (preg_match('/^\d{1,4}-0+/', $mobile)) {
					//不能以0开头
					return false;
				}

				return true;
			}

			return false;
		}
	}
}


if (!function_exists('cmf_send_post')) {
	/**
	 * @param string
	 * @param array
	 * @param string
	 *
	 * @return array
	 */
	function cmf_send_post($url, $data, $client_ip = '')
	{
		$ch = curl_init();

		$params = http_build_query($data);

		$opt = [
			CURLOPT_URL => $url,
			CURLOPT_POST => 1,
			CURLOPT_POSTFIELDS => $params,
			CURLOPT_RETURNTRANSFER => 1,
		];

		if ($client_ip) {
			$opt[CURLOPT_HTTPHEADER] = [
				"CLIENT-IP: {$client_ip}", "X-FORWARDED-FOR: {$client_ip}"
			];
		}
		curl_setopt_array($ch, $opt);
		$json = curl_exec($ch);
		return $json;
	}
}

if (!function_exists('cmf_send_get')) {
	/**
	 * @param string
	 * @param array
	 * @param string
	 *
	 * @return array
	 */
	function cmf_send_get($url,$data = [])
	{
		$ch = curl_init();
		
		$params = '';
		if($data) $params = http_build_query($data);
		
		if($params) $url .= "?".$params;

		$opt = [
			CURLOPT_URL => $url,
			CURLOPT_POST => 0,
			CURLOPT_RETURNTRANSFER => 1,
		];

		curl_setopt_array($ch, $opt);
		$json = curl_exec($ch);
		return $json;
	}
}

/*
 * 出入手机号，返回user_id，也就是注册登录一体接口
 */
if(!function_exists('cmf_mobile_get_userId')){
    /**
     * @param string
     *
     * @return int or false
     */
    function cmf_mobile_get_userId($mobile='',$password = "",$client='',$source='',$ename='',$cn_name='',$cookieId){
        if(!$mobile) return false;
        if(!$password) return false;
        $username = $mobile;
        $cookieId = $cookieId ? $cookieId : cookie('csmonline_cookieid');
        $auth = \app\common\library\Auth::instance();
        if(!$auth->isUser($mobile)){
            // Set default username, email...
            $email = '';
            $extend['entry_platform'] = $client;
            $extend['url_source'] = $source;
            $extend['class_name'] = $ename;
            $extend['class_title'] = $cn_name;
            $extend['sessionid'] = $cookieId;
            if (!$auth->register($username, $password, $email, $mobile,$extend)) {
                return false;
            }
        }
        //$auth->logout();
        $user = \app\common\model\User::get(["mobile" => $mobile]);
        if(!$user) return false;
        return $user->id;
    }
}

/*
 * 输入手机号，返回user_id，也就是注册登录一体接口
 */
if(!function_exists('cmf_userId_set_cookieId')){
    /**
     * @param string
     *
     * @return int or false
     */
    function cmf_userId_set_cookieId($user_id = '',$cookieId = ''){
        if(!$user_id) return false;
        $user = \app\common\model\User::get($user_id);
        $cookieId = $cookieId ? $cookieId : cookie('csmonline_cookieid');
        if(!$user) return false;
        if(!$user->sessionid && $cookieId){
            \think\Db::name('user')->where('id',$user->id)->update(['sessionid'=>$cookieId]);
        }
        return true;
    }
}


/*
 * 输入手机号，返回user_id，也就是注册登录一体接口
 */
if(!function_exists('cmf_cookieId_set_userId')){
    /**
     * @param string
     *
     * @return int or false
     */
    function cmf_cookieId_set_userId($user_id = '',$cookieId = ''){
        if(!$user_id) return false;
        $cookieId = $cookieId ? $cookieId : cookie('csmonline_cookieid');
        $kefu_user = \think\Db::name('kefu_user')->where('sessionid',$cookieId)->find();
        if($cookieId && $kefu_user && !$kefu_user['user_id']){
            \think\Db::name('kefu_user')->where('sessionid',$cookieId)->update(['user_id'=>$user_id]);
        }
        return true;
    }
}

/*
 * 考试宝典返回链接
 */
if(!function_exists('cmf_ksbao_head')){
    function cmf_ksbao_head($enanme='',$client='',$niutype='')
    {
        $guid = session('guid');
        if(!$guid) return false;

        $userAgent = cmf_get_website_value('userAgent');
        //$domain = "http://bywidetest.ksbao.com";  //测试站
        $domain = "http://hzs.ksbao.com";  //正式站
        if($client == 'm'){
            //$url = "https://slb-user-test.ksbao.com/api/user/setLastApp?guid={$guid}&appEName={$enanme}&appVn=0";
            $url = "https://slb-user.ksbao.com/api/user/setLastApp?guid={$guid}&appEName={$enanme}&appVn=0";
            //$go = "http://nktest.ksbao.com/way?token=" .$guid ;
            $go = "https://nk.ksbao.com/way?token=" .$guid .'&niutype='.$niutype;
        }else{
            $go = $domain."/hzsWay?ac=".$userAgent."&token=" .$guid. "&appEName=" . $enanme . "&vn=" . 0 .'&niutype='.$niutype;
        }
        //var_dump($go);exit;
        return $go;
    }
}


/*
 * 考试宝典返回链接
 */
if(!function_exists('cmf_get_video_platform')){
    function cmf_get_video_platform($index = 0)
    {
        $platform = ['1'=>'本站','2'=>'考试宝典','3'=>'助考宝典'];
		if($index){
			return $platform[$index];
		}else{
			return $platform;
		}
    }
}
if (!function_exists('check_ip_allowed')){
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            header('HTTP/1.1 403 Forbidden');
            exit;
        }
    }
}
